package com.gaofans.vertx.boot.web.session;

import com.gaofans.vertx.boot.web.annotation.HttpHandler;
import com.gaofans.vertx.boot.web.config.VertxWebAutoConfig;
import com.gaofans.vertx.boot.web.utils.HttpHandlerOrder;
import com.gaofans.vertx.boot.web.utils.WebConstant;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.SessionHandler;
import io.vertx.ext.web.sstore.ClusteredSessionStore;
import io.vertx.ext.web.sstore.LocalSessionStore;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 创建session的handler
 * @author GaoFans
 */

@AutoConfigureAfter(VertxWebAutoConfig.class)
@Configuration(proxyBeanMethods = false)
public class SessionHandlerAutoConfig {


    @Bean
    @ConfigurationProperties(WebConstant.VERTX_WEB_SESSION_PREFIX)
    public SessionProperties sessionProperties(){
        return new SessionProperties();
    }

    @HttpHandler(order = HttpHandlerOrder.SESSION_CREATE_HANDLER)
    public Handler<RoutingContext> sessionCreateHandler(Vertx vertx,SessionProperties sessionProperties){
        SessionHandler sessionHandler;
        if(vertx.isClustered()){
            sessionHandler = SessionHandler.create(ClusteredSessionStore.create(vertx));
        }else{
            sessionHandler = SessionHandler.create(LocalSessionStore.create(vertx));
        }
        return sessionHandler
                .setSessionTimeout(sessionProperties.getSessionTimeout())
                .setSessionCookiePath(sessionProperties.getSessionCookiePath())
                .setSessionCookieName(sessionProperties.getSessionCookieName())
                .setNagHttps(sessionProperties.isNagHttps())
                .setMinLength(sessionProperties.getMinLength())
                .setLazySession(sessionProperties.isLazySession())
                .setCookieSameSite(sessionProperties.getCookieSameSite())
                .setCookieSecureFlag(sessionProperties.isCookieSecureFlag())
                .setCookieHttpOnlyFlag(sessionProperties.isCookieHttpOnlyFlag());
    }


}
